<template>
    <div class="app-container">
        <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="80px">
            <el-form-item label="机构名称" prop="orgName">
                <el-input v-model="queryParams.orgName" clearable placeholder="请输入机构名称"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <div style="float: right" class="mr20">
                <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery" />
            </div>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button v-hasPerm="['system:SysOrg:add']" plain type="primary" @click="handleAdd"><template #icon>
                        <i-ep-plus />
                    </template>新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-hasPerm="['system:SysOrg:export']" plain type="warning" @click="handleExport"><template
                        #icon>
                        <i-ep-download />
                    </template>导出
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button plain type="danger" @click="refreshCacheOrgFun">
                    <template
                        #icon>
                        <i-ep-refresh/>
                    </template>
                    刷新缓存
                </el-button>
            </el-col>
        </el-row>

        <el-table v-adaptive :data="sysOrgList" stripe highlight-current-row
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :border="true" row-key="orgId"
            :header-cell-style="$headerCellStyle">
            <el-table-column :align="'center'" label="机构名称" prop="orgName" />
            <el-table-column :align="'center'" label="机构code" prop="orgCode" />
            <el-table-column :align="'center'" label="联系人" prop="linkMan" />
            <el-table-column :align="'center'" label="联系人电话" prop="phone" />
            <el-table-column :align="'center'" label="排序" prop="orderNum" />
            <el-table-column :align="'center'" label="备注" prop="remark" />
            <el-table-column :align="'center'" label="状态" width="100">
                <template #default="scope">
                    <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                        @change="handleStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作">
                <template #default="scope">
                    <el-button v-hasPerm="['system:SysOrg:edit']" type="success"
                        @click="handleUpdate(scope.row)"><template #icon>
                            <i-ep-edit />
                        </template>修改
                    </el-button>
                    <el-button v-hasPerm="['system:menu:add']" type="primary" @click="handleAdd(scope.row)"><template
                            #icon><i-ep-plus /></template>新增
                    </el-button>
                    <el-button v-hasPerm="['system:SysOrg:remove']" type="danger" @click="handleDelete(scope.row)">
                        <template #icon>
                            <i-ep-delete />
                        </template>删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList"/>

        <!-- 添加或修改机构对话框 -->
        <el-dialog :close-on-click-modal="false" :title="title" v-model="open" append-to-body width="50%">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="40">
                    <el-col :span="24">
                        <el-form-item label="上级机构" prop="parentId">
                            <select-org-tree :value="form.parentId" style="width: 100%;" v-model="form.orgId"
                                @getTreeSelect="getTreeSelect" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="机构名称" prop="orgName">
                            <el-input v-model="form.orgName" placeholder="请输入机构名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="机构编码" prop="orgCode">
                            <el-input v-model="form.orgCode" :disabled="isEdit" maxlength="16" placeholder="请输入机构code"
                                show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="机构类型" prop="orgClass">
                            <el-select v-model="form.orgClass" filterable placeholder="请选择机构类型">
                                <el-option v-for="dict in dictDataMap['org_class']" :key="dict.dictValue"
                                    :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="机构等级">
                            <el-select v-model="form.orgLevel" placeholder="请选择机构类型">
                                <el-option v-for="dict in dictDataMap['org_level']" :key="dict.dictValue"
                                    :label="dict.dictLabel" :value="dict.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人" prop="linkMan">
                            <el-input v-model="form.linkMan" placeholder="请输入联系人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人电话" prop="phone">
                            <el-input v-model="form.phone" maxlength="11" placeholder="请输入联系人电话" show-word-limit />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人邮箱" prop="email">
                            <el-input v-model="form.email" placeholder="请输入联系人邮箱" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="联系人地址" prop="address">
                            <el-input v-model="form.address" placeholder="请输入联系人地址" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="地区名称" prop="region">
                            <el-input v-model="form.region" placeholder="请输入地区名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="地区编码" prop="regionCode">
                            <el-input v-model="form.regionCode" placeholder="请输入地区编码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="社会信用代码" prop="socialCode">
                            <el-input v-model="form.socialCode" placeholder="请输入社会信用代码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="省" prop="province">
                            <el-input v-model="form.province" placeholder="请输入行政区划代码-省" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="市/区" prop="city">
                            <el-input v-model="form.city" placeholder="请输入行政区划代码-市/区" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="县/区" prop="county">
                            <el-input v-model="form.county" placeholder="请输入行政区划代码-县/区" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="助产标识">
                            <el-radio-group v-model="form.deliverMark">
                                <el-radio v-for="dict in dictDataMap['deliver_mark']" :key="dict.dictValue"
                                    :value="dict.dictValue">{{
                                        dict.dictLabel }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="监管标识">
                            <el-radio-group v-model="form.superviseMark">
                                <el-radio v-for="dict in dictDataMap['supervise_mark']" :key="dict.dictValue"
                                    :value="dict.dictValue">{{
                                        dict.dictLabel }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="救治中心标识">
                            <el-radio-group v-model="form.cureMark">
                                <el-radio v-for="dict in dictDataMap['cure_mark']" :key="dict.dictValue"
                                    :value="dict.dictValue">{{
                                        dict.dictLabel }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="档案关联标识">
                            <el-radio-group v-model="form.archivesMark">
                                <el-radio v-for="dict in dictDataMap['archives_mark']" :key="dict.dictValue"
                                    :value="dict.dictValue">{{
                                        dict.dictLabel }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8" class="select-margin">
                        <el-form-item label="排序" prop="orderNum">
                            <el-input v-model="form.orderNum" placeholder="请输入排序" type="number" />
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="机构logo">
                            <image-upload v-model="form.orgImg" :limit="1" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构介绍" prop="remark">
                            <el-input v-model="form.remark" :rows="8" placeholder="请输入内容" type="textarea" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {
  addSysOrg,
  changeOrgStatus,
  delSysOrg,
  getSysOrg,
  listSysOrg,
  refreshCacheOrg,
  updateSysOrg
} from "@/api/system/sysOrg";
import {useDictStoreHook} from "@/store/modules/dict";

const dictStore = useDictStoreHook();
const { proxy } = getCurrentInstance() as any
const dictDataMap = ref(dictStore.isTypeGetData('org_class', 'archives_mark', 'deliver_mark', 'supervise_mark', 'cure_mark', 'org_level'))
// form 定义的ref
const formRef = ref()
// 按钮loading
const buttonLoading = ref<Boolean>(false)
// 选中数组
const ids = reactive<any[]>([])
// 非单个禁用
const single = ref<Boolean>(true)
// 非多个禁用
const multiple = ref<Boolean>(true)
// 显示搜索条件
const showSearch = ref<Boolean>(true)
// 总条数
const total = ref<number>(0)
// 机构表格数据
const sysOrgList = ref<any[]>([])
// 下拉框机构树
const orgOptions = ref<any[]>([])
// 弹出层标题
const title = ref<String>("")
// 是否编辑
const isEdit = ref<Boolean>(false)
// 是否显示弹出层
const open = ref<Boolean>(false)

// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    orgName: undefined,
    orgCode: undefined,
    email: undefined,
    address: undefined,
    phone: undefined,
    linkMan: undefined,
    applyStatus: "",
    parentId: undefined,
    parentIds: undefined,
    region: undefined,
    regionCode: undefined,
    orgImg: undefined,
    socialCode: undefined,
    province: undefined,
    city: undefined,
    county: undefined,
    deliverMark: undefined,
    superviseMark: undefined,
    cureMark: undefined,
    archivesMark: undefined,
    orgClass: undefined,
    orgLevel: undefined,
    orderNum: undefined,
    status: undefined
})
// 表单参数
let form = ref<any>({
    orgName: undefined,
    orgCode: undefined,
    email: undefined,
    address: undefined,
    phone: undefined,
    linkMan: undefined,
    applyStatus: "",
    parentId: "",
    parentIds: undefined,
    region: undefined,
    regionCode: undefined,
    orgImg: undefined,
    socialCode: undefined,
    province: undefined,
    city: undefined,
    county: undefined,
    deliverMark: "",
    superviseMark: "",
    cureMark: "",
    archivesMark: "",
    orgClass: "",
    orgLevel: "",
    orderNum: undefined,
    status: "",
    orgId: "",
    remark: ""
})

// 表单校验
const rules = reactive({
    orgId: [
        { required: true, message: "机构主键不能为空", trigger: "blur" }
    ],
    parentId: [
        { required: true, message: "上级机构不能为空", trigger: "blur" }
    ],
    orgName: [
        { required: true, message: "机构名称不能为空", trigger: "blur" }
    ],
    orgCode: [
        { required: true, message: "机构code不能为空", trigger: "blur" }
    ]
})
watch(() => form.value.orgCode, (newValue, _oldValue) => {
    // @ts-ignore
    if (newValue) {
        form.value.orgCode = newValue.replace(/[\u4e00-\u9fa5/\s+/]|[^a-zA-Z0-9\u4E00-\u9FA5]/g, "")
    }
}, {
    deep: true
})

/** 查询机构列表 */
function getList() {
    listSysOrg(queryParams.value).then(response => {
        sysOrgList.value = proxy.$handleTree(response.data, "orgId", "orgName")
    });
}

getList();

/** 转换菜单数据结构 */
function normalizer(node: any) {
    if (node.children && !node.children.length) {
        delete node.children
    }
    return {
        id: node.orgId,
        label: node.orgName,
        children: node.children
    }
}
/** 查询机构下拉树结构 */
function getTreeSelect() {
    listSysOrg(queryParams.value).then(response => {
        orgOptions.value = []
        const org = { orgId: 0, value: 0, orgName: '主类目', children: [] }
        org.children = proxy.$handleTree(response.data, "orgId", "orgName")
        orgOptions.value.push(org)
    })
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 角色状态修改
function handleStatusChange(row) {
    let text = row.status === "0" ? "启用" : "停用";
    ElMessageBox.confirm('确认要"' + text + '""' + row.orgName + '"机构吗？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(function () {
        changeOrgStatus(row.orgId, row.status).then(() => {
            ElMessage.success(text + "成功");
        })
    }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
    });
}

// 表单重置
function reset() {
    form.value = {
        orgId: "",
        orgName: undefined,
        orgCode: undefined,
        email: undefined,
        address: undefined,
        phone: undefined,
        linkMan: undefined,
        applyStatus: "0",
        parentId: "",
        parentIds: undefined,
        region: undefined,
        regionCode: undefined,
        orgImg: undefined,
        socialCode: undefined,
        province: undefined,
        city: undefined,
        county: undefined,
        deliverMark: "0",
        superviseMark: "0",
        cureMark: "0",
        archivesMark: "0",
        orgClass: "0",
        orgLevel: "1",
        orderNum: undefined,
        remark: "",
        status: '0'
    }
}

/** 新增按钮操作 */
function handleAdd(row) {
    reset();
    open.value = true;
    isEdit.value = false
    getTreeSelect()
    if (row != null && row.orgId) {
        form.value.parentId = row.orgId
    } else {
        form.value.parentId = "0"
    }
    title.value = "添加机构";
}
/** 修改按钮操作 */
function handleUpdate(row) {
    isEdit.value = true
    reset();
    getTreeSelect()
    const orgId = row.orgId || ids
    getSysOrg(orgId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改机构";
    });
}

/** 提交按钮 */
function submitForm() {
    (formRef.value as any).validate(valid => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.orgId != '') {
                updateSysOrg(form.value).then(_response => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            } else {
                addSysOrg(form.value).then(_response => {
                    ElMessage.success("新增成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            }
        }
    });
}
/** 删除按钮操作 */
function handleDelete(row) {
    const orgIds = row.orgId || ids;
    ElMessageBox.confirm('是否确认删除机构编号为"' + orgIds + '"的数据项？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        delSysOrg(orgIds).then(() => {
            getList();
            ElMessage.success("删除成功");
        })
    }).catch(() => {
    })
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    handleQuery();
}
/** 导出按钮操作 */
function handleExport() {
    // this.download('system/SysOrg/export', {
    //     ...this.queryParams
    // }, `SysOrg_${new Date().getTime()}.xlsx`)
}

function refreshCacheOrgFun() {
    refreshCacheOrg().then((res: any) => {
        ElMessage.success(res.msg);
    })
}

</script>

<script lang="ts">
export default {
    name: "SysOrg"
}
</script>

<style scoped>
.freePic :deep(.hide .el-upload--picture-card) {
    display: none;
}
</style>
